package com.njupt.watcherdemo;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by caolicheng on 15/3/30.
 * 测试需要守护的Service
 */
public class DemoService extends Service {
    private final static String TAG = "demoService";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "service启动！");
        Toast.makeText(this, "Service启动！", Toast.LENGTH_SHORT).show();
        sendBroadcast(new Intent("com.njupt.watcher.ACTION"));
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "进入onDestroy");
        sendBroadcast(new Intent("com.njupt.watcher.destroy"));
        stopForeground(true);
        super.onDestroy();
    }

    @SuppressWarnings("deprecation")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "进入onStartCommand");
        Notification notification = new Notification(R.drawable.ic_launcher, "watcher", System.currentTimeMillis());
        PendingIntent pIntent = PendingIntent.getService(this, 0, intent, 0);
        notification.setLatestEventInfo(this, "watcher运行中", "点击打开watcher", pIntent);
        //让该service前台运行，避免手机休眠时系统自动杀掉该服务
        //如果 id 为 0 ，那么状态栏的 notification 将不会显示。
        startForeground(0, notification);
        return Service.START_REDELIVER_INTENT;
    }

}
